<?php

namespace App\Console\Commands\SiteLocation;

use App\Models\Kms\User\KmsUser;
use App\Models\OpenShop\InvestmentPromotion\OpenShopOrganizationManageModel;
use App\Service\OpenShop\FeishuMini\ProgrammingService;
use App\Service\OpenShop\SiteLocation\GuanyuanDataService;
use Carbon\Carbon;
use Guanguans\Notify\Factory;
use Guanguans\Notify\Messages\FeiShu\CardMessage;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

class SummerSiteRobotPush extends Command
{
    //个人推送
    const SEND_TYPE_PERSONAL = 'personal';


    //团队推送
    const SEND_TYPE_TEAM = 'team';

    //人数限制 最少三个人
    const USER_COUNT = 3;

    //选址数量  最少5家确址
    const SITE_LOCATION_CONFIRM_COUNT = 5;


    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'siteLocation:summer-site-robot-push {type : 设置推送类型`team`或者`personal`}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '夏季选址排行榜推送';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * @return void
     * @throws GuzzleException
     */
    public function handle()
    {
        //设置推送类型
        $type = $this->argument('type');

        switch ($type) {
            case self::SEND_TYPE_PERSONAL:
                $messageBody = $this->personal();
                break;
            case self::SEND_TYPE_TEAM:
                $messageBody = $this->team();
                break;
            default:
                return;
        }
        $this->send(['elements' => $messageBody]);
    }

    /**
     * @return array
     * @throws GuzzleException
     */
    public function personal(): array
    {
        //获得个人排名
        try {
            GuanyuanDataService::setTimeOut(20);
            $personalSiteInfo = GuanyuanDataService::getPersonalSiteLocationConfirm();
        } catch (\Exception $exception) {
            $personalSiteInfo = [];
        }

        //判断是否开启排名赛 rule:确址数大于等于5并且人数大于等于3
        $count = 0;
        foreach ($personalSiteInfo as $personalSite) {
            if ($personalSite['专项城市推荐址门店数'] >= self::SITE_LOCATION_CONFIRM_COUNT) {
                $count++;
            }
        }
        $collectData = collect($personalSiteInfo);

        $frontUser = [];
        $afterUser = [];

        $collectData->sort(function ($a, $b) {
            if ($a['专项城市推荐址门店数'] != $b['专项城市推荐址门店数']) {
                return $b['专项城市推荐址门店数'] <=> $a['专项城市推荐址门店数'];
            }
            return strtotime($a['最晚确址时间']) <=> strtotime($b['最晚确址时间']);
        })->each(function ($item, $count) use (&$frontUser, &$afterUser) {
            $tempUser = $this->getUserInfoByUserName($item['开发经理本名'], $item['昵称'], $count <= 2);  //前三名才生成图片
            if ($count <= 2) {
                //前三名
                $frontUser[] = array_merge($tempUser, ['count' => $item['专项城市推荐址门店数'], 'price' => ((int)$item['基础入围奖']) ? ($item['基础入围奖'] . ' 元') : '-', 'color' => ((int)$item['基础入围奖']) ? 'red' : 'green']);
            } else {
                $afterUser[] = array_merge($tempUser, ['count' => $item['专项城市推荐址门店数'], 'price' => ((int)$item['基础入围奖']) ? ($item['基础入围奖'] . ' 元') : '-', 'color' => ((int)$item['基础入围奖']) ? 'red' : 'green']);
            }
        });


        $totalCount = (int)$collectData->sum('专项城市推荐址门店数');
        if ($count >= self::USER_COUNT) {
            //排行榜开启并推送
            return $this->drawMessageBodyAboutRanking($totalCount, 3 - $count, $frontUser, $afterUser);
        } else {
            return $this->drawMessageBodyAboutPersonal($totalCount, 3 - $count, $frontUser, $afterUser);
        }
    }

    /**
     * @return array
     * @throws GuzzleException
     */
    public function team(): array
    {
        try {
            GuanyuanDataService::setTimeOut(20);
            $teamSiteInfo = GuanyuanDataService::getTeamSiteLocationConfirm();
        } catch (\Exception $exception) {
            $teamSiteInfo = [];
        }
        $collectData = collect($teamSiteInfo);
        $frontTeam   = [];
        $afterTeam   = [];
        $collectData->sort(function ($a, $b) {
            if ($a['本月推荐确址数'] != $b['本月推荐确址数']) {
                return $b['本月推荐确址数'] <=> $a['本月推荐确址数'];
            }
            return strtotime($a['最晚确址时间']) <=> strtotime($b['最晚确址时间']);
        })->each(function ($item, $count) use (&$frontTeam, &$afterTeam) {
            if ($count <= 2) {
                //前三名
                $frontTeam[] = [
                    'teamName' => $item['区域'],
                    'desc'     => $item['团队奖金'],
                    'count'    => $item['本月推荐确址数'],
                    'image'    => $this->getUserInfoByBranchCompany($item['区域']),  //前三名才生成图片
                ];

            } else {
                $afterTeam[] = [
                    'teamName' => $item['区域'],
                    'desc'     => $item['团队奖金'],
                    'count'    => $item['本月推荐确址数'],
                ];
            }
        });
        $totalCount = (int)$collectData->sum('本月推荐确址数');
        return $this->drawMessageBodyAboutTeam($totalCount, $frontTeam, $afterTeam);
    }


    /**
     * 机器人推送消息
     * @param $json
     * @return void
     */
    public function send($json)
    {
        if ('prod' == config('app.env')) {
            //选址培训
            $robot = [
                'url'      => 'https://open.feishu.cn/open-apis/bot/v2/hook/a52e30fc-1d5f-420d-8b58-474f86aec935',
                'urlToken' => 'a52e30fc-1d5f-420d-8b58-474f86aec935',
                'secret'   => 'QEys0nI0mifBeUbk50nhzg'
            ];
        } else {
            //测试
            $robot = [
                'url'      => 'https://open.feishu.cn/open-apis/bot/v2/hook/559b7573-06bf-4e49-b04f-2a3354913ad1',
                'urlToken' => '559b7573-06bf-4e49-b04f-2a3354913ad1',
                'secret'   => 'EMwFuO6vjbfugVgwNBVrHe'
            ];
        }
        $res = Factory::feiShu()
            ->setToken($robot['urlToken'])
            ->setSecret($robot['secret'])
            ->setMessage(new CardMessage($json))
            ->send();

        Log::info('夏季选址专项推送结果' . json_encode($res, JSON_UNESCAPED_UNICODE));
    }


    /**
     * 排行榜推送消息
     * @param int $totalCount
     * @param int $ranking
     * @param array $frontUserInfo
     * @param array $afterUserInfo
     * @return array
     */
    public function drawMessageBodyAboutRanking(int $totalCount, int $ranking, array $frontUserInfo, array $afterUserInfo): array
    {
        $month = Carbon::now()->format('m');
        $body  = [];
        //卡片
        $body[] = [
            "tag"     => "img",
            "img_key" => "img_v2_4936f067-c78c-4ec9-8699-8e4a4133138g",
            "alt"     => [
                "tag"     => "plain_text",
                "content" => ""
            ],
            "mode"    => "fit_horizontal",
            "preview" => true
        ];

        //title
        $body[] = [
            "tag"  => "div",
            "text" => [
                "content" => "**2023 年 {$month} 月夏日战役选址专项业绩排位赛来啦**",
                "tag"     => "lark_md"
            ]
        ];

        //children1
        $body[] = [
            "tag"  => "div",
            "text" => [
                "content" => "**本月累计推荐址确址<font color='red'> {$totalCount} </font>家，排位赛已开启！**\n",
                "tag"     => "lark_md"
            ]
        ];

        //children2
        $body[] = [
            "tag"  => "div",
            "text" => [
                "content" => "**排位赛排行榜**\n",
                "tag"     => "lark_md"
            ]
        ];

        //第1-3名
        $trophy = [
            "｜ 冠军🥇",
            "｜ 亚军🥈",
            "｜ 季军🥉",
        ];

        foreach ($frontUserInfo as $key => $front) {
            $body[] = [
                "tag"              => "column_set",
                "flex_mode"        => "none",
                "background_style" => "default",
                "columns"          => [
                    [
                        "tag"            => "column",
                        "width"          => "weighted",
                        "weight"         => 1,
                        "vertical_align" => "top",
                        "elements"       => [
                            [
                                "tag"           => "img",
                                "img_key"       => $front['userImg'],
                                "alt"           => [
                                    "tag"     => "plain_text",
                                    "content" => ""
                                ],
                                "mode"          => "fit_horizontal",
                                "preview"       => false,
                                "compact_width" => false
                            ]
                        ]
                    ], [
                        "tag"            => "column",
                        "width"          => "weighted",
                        "weight"         => 4,
                        "vertical_align" => "top",
                        "elements"       => [
                            [
                                "tag"     => "markdown",
                                "content" => "**<at id={$front['userId']}></at> {$trophy[$key]}**"
                            ], [
                                "tag"              => "column_set",
                                "flex_mode"        => "none",
                                "background_style" => "grey",
                                "columns"          => [
                                    [
                                        "tag"            => "column",
                                        "width"          => "weighted",
                                        "weight"         => 1,
                                        "vertical_align" => "top",
                                        "elements"       => [
                                            [
                                                "tag"        => "markdown",
                                                "content"    => "**<font color='red'> {$front['count']} 家</font>**\n<font color='grey'>推荐址落位</font>",
                                                "text_align" => "center"
                                            ]
                                        ]
                                    ], [
                                        "tag"            => "column",
                                        "width"          => "weighted",
                                        "weight"         => 1,
                                        "vertical_align" => "top",
                                        "elements"       => [
                                            [
                                                "tag"        => "markdown",
                                                "content"    => "**<font color='{$front['color']}'>{$front['price']}</font>**\n<font color='grey'> 已获奖金</font>",
                                                "text_align" => "center"
                                            ]
                                        ]
                                    ]
                                ]
                            ]
                        ]
                    ]
                ]
            ];
        }

        //后续排名
        foreach ($afterUserInfo as $key => $after) {
            $rank   = $key + 4;
            $body[] = [
                "tag"              => "column_set",
                "flex_mode"        => "none",
                "background_style" => "default",
                "columns"          => [
                    [
                        "tag"            => "column",
                        "width"          => "weighted",
                        "weight"         => 4,
                        "vertical_align" => "top",
                        "elements"       => [
                            [
                                "tag"              => "column_set",
                                "flex_mode"        => "none",
                                "background_style" => "grey",
                                "columns"          => [
                                    [
                                        "tag"            => "column",
                                        "width"          => "weighted",
                                        "weight"         => 1,
                                        "vertical_align" => "top",
                                        "elements"       => [
                                            [
                                                "tag"        => "markdown",
                                                "content"    => "**<at id={$after['userId']}></at>**  \n 第{$rank}名",
                                                "text_align" => "center"
                                            ]
                                        ]
                                    ],
                                    [
                                        "tag"            => "column",
                                        "width"          => "weighted",
                                        "weight"         => 1,
                                        "vertical_align" => "top",
                                        "elements"       => [
                                            [
                                                "tag"        => "markdown",
                                                "content"    => "**<font color='red'> {$after['count']} 家</font>**\n<font color='grey'>推荐址落位</font>",
                                                "text_align" => "center"
                                            ]
                                        ]
                                    ], [
                                        "tag"            => "column",
                                        "width"          => "weighted",
                                        "weight"         => 1,
                                        "vertical_align" => "top",
                                        "elements"       => [
                                            [
                                                "tag"        => "markdown",
                                                "content"    => "**<font color='{$after['color']}'>{$after['price']}</font>**\n<font color='grey'> 已获奖金</font>",
                                                "text_align" => "center"
                                            ]
                                        ]
                                    ]
                                ]
                            ]
                        ]
                    ]
                ]
            ];
        }

        return $body;


    }


    /**
     * 团队消息推送
     * @param int $totalCount
     * @param array $frontTeamInfo
     * @param array $afterTeamInfo
     * @return array
     */
    public function drawMessageBodyAboutTeam(int $totalCount, array $frontTeamInfo, array $afterTeamInfo): array
    {
        $month = Carbon::now()->format('m');
        $body  = [];
        //卡片
        $body[] = [
            "tag"     => "img",
            "img_key" => "img_v2_4936f067-c78c-4ec9-8699-8e4a4133138g",
            "alt"     => [
                "tag"     => "plain_text",
                "content" => ""
            ],
            "mode"    => "fit_horizontal",
            "preview" => true
        ];

        //title
        $body[] = [
            "tag"  => "div",
            "text" => [
                "content" => "**2023 年 {$month} 月夏日战役选址专项业绩团队排行榜**",
                "tag"     => "lark_md"
            ]
        ];

        //children1
        $body[] = [
            "tag"  => "div",
            "text" => [
                "content" => "**本月累计推荐址确址<font color='red'> {$totalCount} </font>家 **\n",
                "tag"     => "lark_md"
            ]
        ];

        //第1-3名
        $trophy = [
            "冠军🥇",
            "亚军🥈",
            "季军🥉",
        ];

        foreach ($frontTeamInfo as $key => $front) {
            $body[] = [
                "tag"              => "column_set",
                "flex_mode"        => "none",
                "background_style" => "default",
                "columns"          => [
                    [
                        "tag"            => "column",
                        "width"          => "weighted",
                        "weight"         => 1,
                        "vertical_align" => "top",
                        "elements"       => [
                            [
                                "tag"           => "img",
                                "img_key"       => $front['image'],
                                "alt"           => [
                                    "tag"     => "plain_text",
                                    "content" => ""
                                ],
                                "mode"          => "fit_horizontal",
                                "preview"       => false,
                                "compact_width" => false
                            ]
                        ]
                    ], [
                        "tag"            => "column",
                        "width"          => "weighted",
                        "weight"         => 4,
                        "vertical_align" => "top",
                        "elements"       => [
                            [
                                "tag"     => "markdown",
                                "content" => "**<font color='green'>@{$front['teamName']} </font> {$trophy[$key]}**"
                            ], [
                                "tag"              => "column_set",
                                "flex_mode"        => "none",
                                "background_style" => "grey",
                                "columns"          => [
                                    [
                                        "tag"            => "column",
                                        "width"          => "weighted",
                                        "weight"         => 1,
                                        "vertical_align" => "top",
                                        "elements"       => [
                                            [
                                                "tag"        => "markdown",
                                                "content"    => "**<font color='red'> {$front['count']} 家</font>**\n<font color='grey'>推荐址落位</font>",
                                                "text_align" => "center"
                                            ]
                                        ]
                                    ], [
                                        "tag"            => "column",
                                        "width"          => "weighted",
                                        "weight"         => 1,
                                        "vertical_align" => "top",
                                        "elements"       => [
                                            [
                                                "tag"        => "markdown",
                                                "content"    => "**{$front['desc']}</font>**</font>",
                                                "text_align" => "center"
                                            ]
                                        ]
                                    ]
                                ]
                            ]
                        ]
                    ]
                ]
            ];
        }


        //后续排名
        foreach ($afterTeamInfo as $key => $after) {
            $rank   = $key + 4;
            $body[] = [
                "tag"              => "column_set",
                "flex_mode"        => "none",
                "background_style" => "default",
                "columns"          => [
                    [
                        "tag"            => "column",
                        "width"          => "weighted",
                        "weight"         => 4,
                        "vertical_align" => "top",
                        "elements"       => [
                            [
                                "tag"              => "column_set",
                                "flex_mode"        => "none",
                                "background_style" => "grey",
                                "columns"          => [
                                    [
                                        "tag"            => "column",
                                        "width"          => "weighted",
                                        "weight"         => 1,
                                        "vertical_align" => "top",
                                        "elements"       => [
                                            [
                                                "tag"        => "markdown",
                                                "content"    => "**<font color='green'> @{$after['teamName']} </font>**  \n 第{$rank}名",
                                                "text_align" => "center"
                                            ]
                                        ]
                                    ],
                                    [
                                        "tag"            => "column",
                                        "width"          => "weighted",
                                        "weight"         => 1,
                                        "vertical_align" => "top",
                                        "elements"       => [
                                            [
                                                "tag"        => "markdown",
                                                "content"    => "**<font color='red'> {$after['count']} 家</font>**\n<font color='grey'>推荐址落位</font>",
                                                "text_align" => "center"
                                            ]
                                        ]
                                    ],
                                    [
                                        "tag"            => "column",
                                        "width"          => "weighted",
                                        "weight"         => 1,
                                        "vertical_align" => "top",
                                        "elements"       => [
                                            [
                                                "tag"        => "markdown",
                                                "content"    => "**{$after['desc']}</font>**</font>",
                                                "text_align" => "center"
                                            ]
                                        ]
                                    ]
                                ]
                            ]
                        ]
                    ]
                ]
            ];
        }
        return $body;
    }


    /**
     * 个人排行榜推送
     * @param int $totalCount
     * @param int $ranking
     * @param array $frontUserInfo
     * @param array $afterUserInfo
     * @return array
     */
    public function drawMessageBodyAboutPersonal(int $totalCount, int $ranking, array $frontUserInfo, array $afterUserInfo): array
    {
        $month = Carbon::now()->format('m');

        $body = [];
        //卡片
        $body[] = [
            "tag"     => "img",
            "img_key" => "img_v2_4936f067-c78c-4ec9-8699-8e4a4133138g",
            "alt"     => [
                "tag"     => "plain_text",
                "content" => ""
            ],
            "mode"    => "fit_horizontal",
            "preview" => true
        ];

        //title
        $body[] = [
            "tag"  => "div",
            "text" => [
                "content" => "**2023 年 {$month} 月夏日战役选址专项业绩排行榜来啦**",
                "tag"     => "lark_md"
            ]
        ];

        //children1
        $body[] = [
            "tag"  => "div",
            "text" => [
                "content" => "**本月累计推荐址确址<font color='red'> {$totalCount} </font>家，还差<font color='red'> {$ranking} </font>名开启排位赛！**\n",
                "tag"     => "lark_md"
            ]
        ];

        //children2
        $body[] = [
            "tag"  => "div",
            "text" => [
                "content" => "**累计推荐址确址排行榜**\n",
                "tag"     => "lark_md"
            ]
        ];

        //第1-3名
        $trophy = [
            "｜ 冠军🥇",
            "｜ 亚军🥈",
            "｜ 季军🥉",
        ];

        foreach ($frontUserInfo as $key => $front) {
            $body[] = [
                "tag"              => "column_set",
                "flex_mode"        => "none",
                "background_style" => "default",
                "columns"          => [
                    [
                        "tag"            => "column",
                        "width"          => "weighted",
                        "weight"         => 1,
                        "vertical_align" => "top",
                        "elements"       => [
                            [
                                "tag"           => "img",
                                "img_key"       => $front['userImg'],
                                "alt"           => [
                                    "tag"     => "plain_text",
                                    "content" => ""
                                ],
                                "mode"          => "fit_horizontal",
                                "preview"       => false,
                                "compact_width" => false
                            ]
                        ]
                    ], [
                        "tag"            => "column",
                        "width"          => "weighted",
                        "weight"         => 4,
                        "vertical_align" => "top",
                        "elements"       => [
                            [
                                "tag"     => "markdown",
                                "content" => "**<at id={$front['userId']}></at> {$trophy[$key]}**"
                            ], [
                                "tag"              => "column_set",
                                "flex_mode"        => "none",
                                "background_style" => "grey",
                                "columns"          => [
                                    [
                                        "tag"            => "column",
                                        "width"          => "weighted",
                                        "weight"         => 1,
                                        "vertical_align" => "top",
                                        "elements"       => [
                                            [
                                                "tag"        => "markdown",
                                                "content"    => "**<font color='red'> {$front['count']} 家</font>**\n<font color='grey'>推荐址落位</font>",
                                                "text_align" => "center"
                                            ]
                                        ]
                                    ]
                                ]
                            ]
                        ]
                    ]
                ]
            ];
        }

        //后续排名
        foreach ($afterUserInfo as $key => $after) {
            $rank   = $key + 4;
            $body[] = [
                "tag"              => "column_set",
                "flex_mode"        => "none",
                "background_style" => "default",
                "columns"          => [
                    [
                        "tag"            => "column",
                        "width"          => "weighted",
                        "weight"         => 4,
                        "vertical_align" => "top",
                        "elements"       => [
                            [
                                "tag"              => "column_set",
                                "flex_mode"        => "none",
                                "background_style" => "grey",
                                "columns"          => [
                                    [
                                        "tag"            => "column",
                                        "width"          => "weighted",
                                        "weight"         => 1,
                                        "vertical_align" => "top",
                                        "elements"       => [
                                            [
                                                "tag"        => "markdown",
                                                "content"    => "**<at id={$after['userId']}></at>**  \n 第{$rank}名",
                                                "text_align" => "center"
                                            ]
                                        ]
                                    ],
                                    [
                                        "tag"            => "column",
                                        "width"          => "weighted",
                                        "weight"         => 1,
                                        "vertical_align" => "top",
                                        "elements"       => [
                                            [
                                                "tag"        => "markdown",
                                                "content"    => "**<font color='red'> {$after['count']} 家</font>**\n<font color='grey'>推荐址落位</font>",
                                                "text_align" => "center"
                                            ]
                                        ]
                                    ]
                                ]
                            ]
                        ]
                    ]
                ]
            ];
        }

        return $body;

    }


    /**
     * 通过花名或者名字获得基本信息
     * @param string $userName
     * @param string $nikeName
     * @param bool $img
     * @return array
     */
    public function getUserInfoByUserName(string $userName, string $nikeName, bool $img = false): array
    {
        //花名唯一优先级高
        $userInfo = KmsUser::query()
            ->where('nickname', $nikeName)
            ->orWhere('name', $userName)
            ->select(['userId', 'avatar'])
            ->first();

        if ($userInfo === null) {
            return [
                'userId'  => '',
                'userImg' => 'img_v2_b733816b-4ec5-4eed-8ba8-6582f1bc59bg'
            ];
        }

        $image = '';
        if ($img === true) {
            $image = Cache::rememberForever('feishu:user:avatar:imgKey:' . $userName . '-' . $nikeName . '-' . md5($userInfo->avatar), function () use ($userInfo) {
                return ProgrammingService::getFeishuImageKey($userInfo->avatar);
            });
        }

        return [
            'userId'  => $userInfo->userId,
            'userImg' => $image
        ];
    }


    /**
     * 通过分公司获得基本信息
     * @param string $branchCompanyName
     * @return string
     */
    public function getUserInfoByBranchCompany(string $branchCompanyName): string
    {
        //获得负责人ID
        if (in_array($branchCompanyName, ['江苏北分公司', '江苏南分公司'])) {
            $branchCompanyName = '江苏分公司';
        }
        $managerUserId = (int)OpenShopOrganizationManageModel::query()
            ->where('name', $branchCompanyName)
            ->value('operationUid');
        $imageKey      = 'img_v2_b733816b-4ec5-4eed-8ba8-6582f1bc59bg';
        if ($managerUserId == 0) {
            return $imageKey;
        }
        //获得负责人信息
        $managerUserInfo = KmsUser::query()->where('rmsUserId', $managerUserId)->first();

        if ($managerUserInfo === null) {
            return $imageKey;
        }
        return Cache::rememberForever('feishu:user:avatar:imgKey:' . $managerUserInfo->name . '-' . $managerUserInfo->nickname . '-' . md5($managerUserInfo->avatar), function () use ($managerUserInfo) {
            return ProgrammingService::getFeishuImageKey($managerUserInfo->avatar);
        });
    }


}
